package project.jsf;

import project.entity.Editor;
import project.jsf.util.JsfUtil;
import project.jsf.util.PaginationHelper;
import project.ejbs.EditorFacade;

import java.io.Serializable;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import project.ejbs.Session;
import project.entity.Papel;

@ManagedBean(name = "editorController")
@SessionScoped
public class EditorController implements Serializable {

    private Editor current;
    private DataModel items = null;
    @EJB
    private project.ejbs.EditorFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @EJB
    private Session sessao;
    private String confirmarPassword;

    public EditorController() {
    }

    public Editor getSelected() {
        if (current == null) {
            current = new Editor();
            selectedItemIndex = -1;
        }
        return current;
    }

    private EditorFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Editor) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Editor();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            if (!current.getEmail().matches("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")){
                JsfUtil.addErrorMessage("E-Mail com formato inválido.");
                return null;
            }
            if (current.getDataNascimento().after(new Date())){
                JsfUtil.addErrorMessage("Data de nascimento inválida! (dd/mm/yyyy)");
                return null;
            }
            if(current.getPassword().equals(confirmarPassword) && !current.getPassword().equals("")){
                current.setPasswordHash(current.getPassword());
                current.setPapel(new Papel(current, Papel.Perfil.Editor));
                current.setDataRegisto(new Date());
                getFacade().create(current);
                JsfUtil.addSuccessMessage("Conta registada com sucesso.");
                return "/evento/List";
            }
            
            if (current.getPassword().equals(""))
                JsfUtil.addErrorMessage("O campo da password não pode estar vazio.");
            else
                JsfUtil.addErrorMessage("A confirmação de password está errada.");
            
            return null;
            
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Ocurreu um erro ao tentar registar. Verifique o username.");
            return null;
        }
    }

    public String prepareEdit() {
        current = (Editor) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    /**
     * @return the confirmarPassword
     */
    public String getConfirmarPassword() {
        return "";
    }

    /**
     * @param confirmarPassword the confirmarPassword to set
     */
    public void setConfirmarPassword(String confirmarPassword) {
        this.confirmarPassword = confirmarPassword;
    }

    @FacesConverter(forClass = Editor.class)
    public static class EditorControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            EditorController controller = (EditorController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "editorController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.String getKey(String value) {
            java.lang.String key;
            key = value;
            return key;
        }

        String getStringKey(java.lang.String value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Editor) {
                Editor o = (Editor) object;
                return getStringKey(o.getUsername());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + EditorController.class.getName());
            }
        }
    }
}
